package cn.itcast.service.impl;

import cn.itcast.mapper.StudentMapper;
import cn.itcast.pojo.ClazzOption;
import cn.itcast.pojo.PageResult;
import cn.itcast.pojo.Student;
import cn.itcast.pojo.StudentQueryParam;
import cn.itcast.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        //设置分页参数
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        //列表查询
        List<Student> studentList = studentMapper.page(studentQueryParam);
        //强转
        Page<Student> studentPage = (Page<Student>) studentList;

        PageResult<Student> pageResult = PageResult.<Student>builder().rows(studentPage.getResult())
                .total(studentPage.getTotal()).build();
        return pageResult;
    }

    @Override
    public void save(Student student) {
        //填充基本字段
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.save(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);

    }

    @Override
    public void deleteBatch(Integer[] ids) {
        //数组转成集合
        List<Integer> idsList = Arrays.asList(ids);
        studentMapper.deleteBatch(idsList);
    }

    @Override
    @Transactional
    public void violation(Integer id, Integer score) {

        //1.违纪扣分 包含违纪次数+1
        //做一个判断，分数大于>=0才生效
        if (score <= 0) {
            throw new RuntimeException("参数不能小于等于0");
        }
        studentMapper.violationAddScore(id, score);

    }

    @Override
    public ClazzOption studentCountData() {
        List<Map> mapList  = studentMapper.studentCountData();
        List<Object> clazzList = mapList.stream().map(map -> map.get("clazz")).collect(Collectors.toList());
        List<Object> dataList = mapList.stream().map(map -> map.get("count")).collect(Collectors.toList());
        ClazzOption clazzOption = ClazzOption.builder().clazzList(clazzList)
                .dataList(dataList).build();

        return clazzOption;
    }

    @Override
    public List<Map> studentDegreeData() {

        return studentMapper.studentDegreeData();
    }
}
